A matrix
of size n * n is given. Find the sum of all its positive elements.
Input. The first line contains a single integer n (1 ≤ n ≤ 100). The next n
lines contain the elements of the n *
n matrix. Each element is an integer
with an absolute value not exceeding 100.
Output. Print the sum
of all positive elements in the matrix.
Sample input |
Sample output |
3 4 -2 5 1 -4 -12 0 1 -3 |
11 |
array – 2-dim
Algorithm
analysis
Using a
double loop, compute the sum
of the positive elements in the matrix (two-dimensional array).
Algorithm
implementation
Declarw a two-dimensional array m.
int m[101][101];
Read the input data. In the
variable s, compute the sum
of all its positive elements.
scanf("%d",&n);
s = 0;
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
{
scanf("%d",&m[i][j]);
if (m[i][j] > 0) s = s + m[i][j];
}
Print the answer.
printf("%d\n",s);
Java implementation
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
int n = con.nextInt();
int m[][] = new int[n][n];
int s = 0;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
{
m[i][j] = con.nextInt();
if (m[i][j] > 0) s = s + m[i][j];
}
System.out.println(s);
con.close();
}
}
Java implementation – threads
import
java.util.*;
class
SumRow extends Thread
{
int[][] m;
int row, res;
SumRow(int[][] m, int row)
{
this.m = m;
this.row = row;
}
public void
run()
{
res = 0;
for(int i = 0; i < m[0].length; i++)
if (m[row][i] > 0) res = res + m[row][i];
}
public int GetValue()
{
return res;
}
}
public class Main
{
public static void main(String[] args) throws InterruptedException
{
Scanner con = new Scanner(System.in);
int n = con.nextInt();
int m[][] = new int[n][n];
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
m[i][j] = con.nextInt();
SumRow s[] = new SumRow[n];
for(int i = 0; i < n; i++)
{
s[i] = new SumRow(m,i);
s[i].start();
}
for(int i = 0; i < n; i++)
s[i].join();
int sum = 0;
for(int i = 0; i < n; i++)
sum = sum + s[i].GetValue();
System.out.println(sum);
con.close();
}
}
Python implementation
Read the input data.
n = int(input())
a = [list(map(int, input().split())) for _ in
range(n)]
In the variable s, compute the sum of all the positive
elements in the matrix.
sum = 0
for i in
range(n):
for
j in range(n):
if
a[i][j] > 0: sum += a[i][j]
Print the answer.
print(sum)
Python implementation – list
comprehension
Read the input data.
n = int(input())
a = [list(map(int, input().split())) for _ in
range(n)]
Compute the sum of all the positive elements in the matrix.
sum = sum(a[i][j] for i in range(n) for j in range(n) if a[i][j] > 0)
Print the answer.
print(sum)